import { da } from "@faker-js/faker";
import MedicalRecord from "../models/medicalRecord.js"
import User from "../models/user.js"
import Result from "../utils/result.js"

const medicalRecordService = {
    async getMedicalRecord(userId) {
        try{
            const user = await User.findOne({
                where: {
                    id: userId
                }
            });
            if(!user){
                return Result.notfound('用户不存在');
            }

            const result = await MedicalRecord.findAll({
                where: {
                    userId: userId
                }
            });

            return Result.success(result, '获取病历成功');
        }catch(err){
            return Result.error(err.message);
        }
    },
    async addMedicalRecord(data) {
        console.log('addMedicalRecord',data)

        try{
            const user = await User.findOne({
                where: {
                    id: data.userId
                }
            });
            if(!user){
                return Result.notfound('用户不存在');
            }
            const result = await MedicalRecord.create(data);
            // console.log("addMedicalRecord success:",result);
            return Result.success(result, '添加病历成功');
        }catch(err){
            return Result.error(err.message);
        }
    },
    async delMedicalRecord(recordId,userId) {
        try{
            const user = await  User.findOne({
                where: {
                    id: userId
                }
            });
            if(!user){
                return Result.notfound('用户不存在');
            }
            const record = await MedicalRecord.findOne({
                where: {
                    id: recordId
                }
            });
            if(!record){
                return Result.notfound('病例不存在');
            }
            if((record.userId != userId)){
                console.log(record.userId,userId);
                return Result.forbidden('该病例不属于该用户');
            }

            await record.destroy();
            console.log(`del medicalRecord ${recordId} success`);
            return Result.success(recordId,'删除病例成功').toObject();

        }catch(err){
            return Result.error(err.message);
        }
    },
}


export default medicalRecordService;